package com.loe.mvp.util;

import android.text.InputFilter;
import android.text.Spanned;

/**
 * 浮点输入长度限制
 *
 * @author 章路顺
 * @since 2021/9/4-15:27
 */
public class DecimalLimitFilter implements InputFilter
{
    private int limit = 2;

    public DecimalLimitFilter()
    {
    }

    public DecimalLimitFilter(int limit)
    {
        this.limit = limit;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
    {
        try
        {
            // 删除等特殊字符，直接返回
            if ("".equals(source.toString()))
            {
                return null;
            }
            String dValue = dest.toString();
            String[] splitArray = dValue.split("\\.");
            if (splitArray.length > 1)
            {
                String dotValue = splitArray[1];
                int diff = dotValue.length() + 1 - limit;
                if (diff > 0)
                {
                    return source.subSequence(start, end - diff);
                }
            }
        }catch (Exception e)
        {
        }
        return null;
    }
}
